package kyssion.leetcode.num201_250;

import java.util.Stack;

public class code227_基本计算器2_X {
    public static void main(String[] args) {
        System.out.println(new code227_基本计算器2_X().calculate("0-2147483647"));
    }

    public int calculate(String s) {
        char[] item = s.toCharArray();
        Stack<Integer> num = new Stack<>();
        Stack<Character> word = new Stack<>();
        for (int a = 0; a < item.length; a++) {
            if (item[a] == ' ') {
                continue;
            }
            if (item[a] == '-') {
                while (!word.isEmpty()) {
                    int nu = run(num.pop(), num.pop(), word.pop());
                    num.add(nu);
                }
                word.add(item[a]);
            } else if (item[a] == '+') {
                while (!word.isEmpty()) {
                    int nu = run(num.pop(), num.pop(), word.pop());
                    num.add(nu);
                }
                word.add(item[a]);
            } else if (item[a] == '*') {
                if (!word.isEmpty()&&(word.peek() == '*' || word.peek() == '/')) {
                    while (!word.isEmpty()) {
                        int nu = run(num.pop(), num.pop(), word.pop());
                        num.add(nu);
                    }
                }
                word.add(item[a]);
            } else if (item[a] == '/') {
                if (!word.isEmpty()&&(word.peek() == '*' || word.peek() == '/')) {
                    while (!word.isEmpty()) {
                        int nu = run(num.pop(), num.pop(), word.pop());
                        num.add(nu);
                    }
                }
                word.add(item[a]);
            } else {
                int iii = 0;
                int b;
                for (b = a; b < item.length; b++) {
                    if (item[b] >= '0' && item[b] <= '9') {
                        iii = iii * 10 + item[b] - '0';
                    } else {
                        break;
                    }
                }
                a = b - 1;
                num.add(iii);
            }
        }
        while (!word.isEmpty()) {
            int nu = run(num.pop(), num.pop(), word.pop());
            num.add(nu);
        }
        return num.pop();
    }

    private int run(Integer pop, Integer pop1, Character pop2) {
        if (pop2 == '+') {
            return pop + pop1;
        } else if (pop2 == '-') {
            return pop1 - pop;
        } else if (pop2 == '*') {
            return pop * pop1;
        } else {
            return pop1 / pop;
        }
    }
}
